﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LinqExpressions = System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Xant.Querier.Core;

namespace Xant.Querier.Utils
{
    public class TypeInfoHelper<T>
    {
        private Field GetProperty(LinqExpressions.Expression expression)
        {
            /*if (expression is UnaryExpression)
            {
                var operand = (expression as UnaryExpression).Operand;
                operand.Type.ToString();
            }
            */
            var memberExpression = expression as LinqExpressions.MemberExpression;
            if (memberExpression == null)
            {
                throw new ArgumentException("NotMemberAccessExpression");
            }

            var property = memberExpression.Member as PropertyInfo;
            if (property == null)
            {
                throw new ArgumentException("ExpressionNotProperty");
            }

            var getMethod = property.GetGetMethod(true);
            if (getMethod.IsStatic)
            {
                throw new ArgumentException("StaticExpression");
            }

            string path = expression.ToString();
            path = path.Substring(path.IndexOf('.') + 1);
            return new Field(path, property.PropertyType);
        }


        /// <summary>
        /// 从Linq表达式中解析出对象属性名
        /// </summary>
        /// <remarks>如果不定义 TFieldType 版本，那么类似helper.GetProperty(p=>p.Date)这样的表达式将被包装为p=>Convert(p.Date)，导致解析失败</remarks>
        /// <typeparam name="TFieldType"></typeparam>
        /// <param name="propertyExpression"></param>
        /// <returns></returns>
        public Field GetProperty<TFieldType>(LinqExpressions.Expression<Func<T, TFieldType>> propertyExpression)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }
            return GetProperty(propertyExpression.Body);
        }

        /*废止
        public Field GetProperty(Expression<Func<T, object>> propertyExpression)
        {
            //var body = exp.Body.ToString();
            //return body.Substring(body.LastIndexOf(".") + 1);
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }
            return GetProperty(propertyExpression.Body);
        }*/

    }
}
